package com.startdima.user.infrastructure.utils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.startdima.user.domain.entity.UserInfo;
import com.startdima.user.infrastructure.exception.BusinessException;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class JwtTokenUtil {
	
    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";
    
    @Value("${jwt.secret:demo-secret}")
    private String secret;
    
    /**
     * 默认7天过期
     */
    @Value("${jwt.expiration:604,800}")
    private Long expiration;
 
    /**
     * 根据负责生成JWT的token
     */
    public String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }
 
    /**
     * 从token中获取JWT中的负载
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}",token);
        }
        return claims;
    }
 
    /**
     * 生成token的过期时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }
 
    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username =  claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }
 
    /**
     * 验证token是否还有效
     *
     * @param token       客户端传入的token
     * @param UserInfo 从数据库中查询出来的用户信息
     */
    public void validateToken(String token, UserInfo UserInfo) {
        String username = getUserNameFromToken(token);
        boolean matched = Objects.equals(username, UserInfo.getUsername());
        if (!matched) {
        	throw new BusinessException("token信息不匹配");
		}
    }
 
    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
    	Date expiredDate;
    	// 解析不出过期时间，默认认定为失效
    	try {
    		expiredDate = getExpiredDateFromToken(token);
		} catch (Exception e) {
			return true;
		}
        return expiredDate.before(new Date());
    }
    
    /**
     * 验证token是否超时，超时则抛出异常BusinessException
     * @param token Token
     */
    public void checkTokenExpired(String token) {
    	boolean expired = isTokenExpired(token);
    	if (expired) {
			throw new BusinessException(401, "token已超时失效");
		}
    }
 
    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }
 
    /**
     * 根据用户信息生成token
     */
    public String generateToken(UserInfo UserInfo) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, UserInfo.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }
 
    /**
     * 判断token是否可以被刷新
     */
    public boolean canRefresh(String token) {
        return !isTokenExpired(token);
    }
 
    /**
     * 刷新token
     */
    public String refreshToken(String token) {
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

}
